package com.it.controller.admin;

import com.it.admin.AdminUserService;
import com.it.bean.ConstEnum;
import com.it.bean.R;
import com.it.bean.RestStatusEnum;
import com.it.pojo.User;
import com.it.pojo.params.RegisterQuery;
import com.it.pojo.params.user.UserEditQuery;
import com.it.pojo.params.user.UserListQuery;
import com.it.pojo.params.user.UserSaveQuery;
import com.it.pojo.vo.user.AdminUserEditVO;
import com.it.pojo.vo.user.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("admin/user")
@Api(value = "v1", tags = "登录相关接口")
public class AdminUsersController {


    @Resource
    private AdminUserService adminUserService;
    private static final Logger logger = LoggerFactory.getLogger(AdminUsersController.class);

    @PostMapping("login")
    @ApiOperation(value = "登录接口", notes = "登录以后返回token")
    public R<?> login(@RequestParam @ApiParam(value = "用户名") String username,
                      @RequestParam @ApiParam(value = "密码") String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return R.error(RestStatusEnum.PARAMS_ERROR.getMsg());
        }
        String token = adminUserService.login(username, password);
//         等于32位表示返回的是token，否则就是相对应的错误信息
        return token.length() == Integer.parseInt(ConstEnum.TOKEN_LENGTH.getResult())
                ? R.success("登录成功", token) : R.error(token);

    }

    @PostMapping("register")
    @ApiOperation(value = "注册接口", notes = "注册")
    public R<?> register(@RequestBody RegisterQuery registerQuery) {
        if (registerQuery == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR.getMsg());
        }
        String nickname = registerQuery.getNickname();
        String password = registerQuery.getPassword();
        String username = registerQuery.getUsername();
        logger.info("registerq={}", registerQuery);
        if (StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        return adminUserService.register(registerQuery) > 0 ? R.success("注册成功") : R.error("注册失败");

    }

    @PostMapping("list")
    @ApiOperation(value = "获取分页用户信息", notes = "获取分页用户信息")
    public R<?> listUsers(@RequestBody UserListQuery userQuery) throws ParseException {
        if (userQuery.getPageNum() <= 0 || userQuery.getLimit() <= 0) {
            return R.error(RestStatusEnum.PAGE_ERROR);
        }
        Map<String, Object> map = adminUserService.listUsers(userQuery);
        return R.success("成功", map);
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "根据用户id删除", notes = "根据用户id删除")
    public R<?> delete(@RequestParam Integer userId) {
        if (userId == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        return adminUserService.deleteUserById(userId) > 0 ? R.success() : R.error();
    }

    @PostMapping("save")
    @ApiOperation(value = "添加用户", notes = "添加用户")
    public R<?> saveUser(@RequestBody UserSaveQuery userSaveQuery) {
        if (userSaveQuery == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        logger.info("{}", userSaveQuery);
        // TODO 参数校验就不做了
        User user = new User();
        BeanUtils.copyProperties(userSaveQuery, user);
        return adminUserService.saveUser(user) > 0 ? R.success() : R.error();
    }

    @GetMapping("{userId}")
    @ApiOperation(value = "根据用户id查询", notes = "根据用户id查询")
    public R<?> getUser(@PathVariable("userId") Integer userId) {
        if (userId <= 0) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        AdminUserEditVO adminUserEditVO = adminUserService.getUserById(userId);
        return R.success("成功", adminUserEditVO);
    }

    @PutMapping("")
    @ApiOperation(value = "根据用户id修改用户信息", notes = "根据用户id修改用户信息")
    public R<?> edit(@RequestBody UserEditQuery userEditQuery) {
        if (userEditQuery == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        // TODO 参数校验暂时不做
        User user = new User();
        BeanUtils.copyProperties(userEditQuery, user);
        return adminUserService.updateUserById(user) > 0 ? R.success() : R.error();
    }

    @GetMapping("info")
    @ApiOperation(value = "根据token获取用户信息", notes = "根据token获取用户信息")

    public R<?> info(@RequestParam("token") String token) {
        if (StringUtils.isEmpty(token)) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        UserInfoVO userInfoVO = adminUserService.getUserByToken(token);
        return userInfoVO != null ? R.success("成功", userInfoVO) : R.error("失败", userInfoVO);
    }

    @GetMapping("logout")
    @ApiOperation(value = "登出接口", notes = "登出接口")

    public R<?> logout(@RequestParam("userId") Integer userId) {
        if (userId == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        System.out.println("userId = " + userId);
        return adminUserService.logout(userId) > 0 ? R.success("登出成功") : R.error("登出失败");
    }
}
